package com.niguang.work.api.weChatTemplate.abstracts;

import com.alibaba.fastjson.JSON;
import com.niguang.common.util.HttpClientUtil;
import com.niguang.work.api.vo.WechatTemplateMsg;
import com.niguang.work.api.vo.result.TemplateMsgResult;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;

@Slf4j
@Component
public abstract class SendWeChat {

    @Resource
    private WxMpService wxMpService;

    /**
     * 微信模板通知
     */
    private final static String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";


    /**
     * 发送消息模板
     *
     * @param wechatTemplateMsg
     * @return
     */
    public boolean sendWeChatInfo(WechatTemplateMsg wechatTemplateMsg) {
        try {
            String accessToken = wxMpService.getAccessToken();
            String weChatUrl = String.format(url, accessToken);
            String result = HttpClientUtil.sendPost(weChatUrl, JSON.toJSONString(wechatTemplateMsg));
            log.info("微信消息推送返回信息：{}", result);
            TemplateMsgResult templateMsgResult = JSON.parseObject(result, TemplateMsgResult.class);
            if (templateMsgResult.getErrcode() != 0) {
                log.info("微信推送失败,失败原因：{}", templateMsgResult.getErrmsg());
                return false;
            } else {
                log.info("微信推送成功，返回Msgid：{}", templateMsgResult.getMsgid());
            }
            return true;
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return false;
    }

}
